package com.wisemoresystem.seal.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.ne.framework.data.page.Page;
import org.ne.framework.data.util.ChkTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sun.misc.BASE64Decoder;

import com.wisemoresystem.seal.action_rest.BMPLoader;
import com.wisemoresystem.seal.base.service.BaseService;
import com.wisemoresystem.seal.config.Config;
import com.wisemoresystem.seal.model.t_file;
import com.wisemoresystem.seal.model.t_seal;
import com.wisemoresystem.seal.model.t_seal_stop;
import com.wisemoresystem.seal.model.t_seal_user;
import com.wisemoresystem.seal.model.t_seal_user_use;
import com.wisemoresystem.seal.model.t_user;
import com.wisemoresystem.seal.util.DateTools;
import com.wisemoresystem.seal.util.SpringTools;
import com.wisemoresystem.seal.web.WebTools;

@Service
public class SealSetService extends BaseService {
	
	@Autowired
	private BankService bService;
	@Autowired
	private SealTypeConfigService sService;
	
	public List<Map<String, Object>> selectSealList(String srh_name,Page page) {
		String sql = "select t.*,ts.title,tst.name seal_type_name,tstc.name seal_type_config_name ,tu.uname,tstc.note snote from t_seal t "
				+ " left outer join t_seal_new ts on t.status=0 and t.seal_new_id=ts._id "
				+ " left outer join t_user tu on t.save_user_id=tu._id and tu.status=0 "
				+ " left join t_seal_type tst on ts.seal_type_id=tst._id "
				+ " left join t_seal_type_config tstc on ts.seal_type_config_id=tstc._id "
				+ " where t.status=0 and t.bank_id=? and t.name like ? order by t.created desc ";
		List<String> params = new ArrayList<String>();
		
		params.add(WebTools.getCurrentBankId());
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.name like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(),page);
		return list;
	}
	
	public List<Map<String, Object>> selectSealList1(String srh_name,Page page) {
		String sql = "select t.*,ts.title,tst.name seal_type_name,tstc.name seal_type_config_name ,tu.uname,tstc.note snote from t_seal t "
				+ " left outer join t_seal_new ts on t.status=0 and t.seal_new_id=ts._id "
				+ " left outer join t_user tu on t.save_user_id=tu._id and tu.status=0 "
				+ " left join t_seal_type tst on ts.seal_type_id=tst._id "
				+ " left join t_seal_type_config tstc on ts.seal_type_config_id=tstc._id "
				+ " where t.status=0 and t.bank_id=? and t.name like ? order by t.created desc ";
		List<String> params = new ArrayList<String>();
		
		params.add("4028814a4b25516c014b255ff9d40005");
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.name like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(),page);
		return list;
	}
	//核对印章
	public List<Map<String,Object>> chkUserSeal(){
		String sql = "select * form t_seal "
				+ " ";
		
		List<String> params = new ArrayList<String>();
		
		List<Map<String,Object>> list = jt.queryForList(sql,params.toArray());
		
		return list;
	}
	
	//安装卸载列表
	public List<Map<String, Object>> selectSealInstallList(String srh_name,Page page) {
		String sql = "select tuu.position,tm.code,t.*,tsu.use_user_id,tu.uname,ts.title,tst.name seal_type_name,tstc.user_way,tstc.name seal_type_config_name,tstc.note snote,ts.desc_s from t_seal t "
				+ " left join t_seal_new ts on t.status=0 and t.seal_new_id=ts._id "
				+ " left join t_seal_user tsu on tsu.seal_id=t._id and tsu.flag in('已领取','使用中') "
				+ " left join t_seal_user_use tuu on tuu.seal_user_id=tsu._id and tuu.flag not in('已卸载') "
				+ " left join t_mac tm on tuu.mac_id=tm._id "
				+ " left join t_seal_type tst on ts.seal_type_id=tst._id "
				+ " left join t_seal_type_config tstc on ts.seal_type_config_id=tstc._id "
				+ " left join t_user tu on tu._id=tsu.use_user_id "
				+ " where t.status=0 and t.bank_id=? and t.name like ? and t.flag_use in('已领取','使用中') and t.flag_use_status in('未安装','已安装') and tsu.use_user_id=? "
				+ " order by t.created asc ";
		List<String> params = new ArrayList<String>();
		
		params.add(WebTools.getCurrentBankId());
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.name like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		params.add(WebTools.getCurrentUserId());
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(),page);
		return list;
	}
	//授权者_id
	public String selectSealUserAuthList(String user_id){
		
		String sql ="select distinct(t.begin_user_id) from t_seal_auth t "
				+ " where t.status=0 and t.bank_id=? and t.end_user_id=? "
				+ " and t.flag='生效' and ? between t.time_get and t.time_back "
				+ " order by t.created desc";
		
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String today = df.format(c.getTime());
		
		List<String> params = new ArrayList<String>();
		params.add(WebTools.getCurrentBankId());
		params.add(user_id);
		params.add(today);
		
		List<Map<String,Object>> list = jt.queryForList(sql,params.toArray());
		String ids = "'"+user_id+"'";
		if(ChkTools.isNotNull(list)){
			for(Map<String,Object> id:list){
				ids = ids+",'"+id.get("begin_user_id")+"'";
			}
		}
		return ids;
	}
	
	//启用
	public List<Map<String, Object>> selectSealStartList(String srh_name,Page page) {
		String sql = "select t.* from t_seal t "
				+ " where t.status=0 and t.bank_id=? and t.name like ? and t.flag_stop='暂时停用 ' and t.flag='停用' order by t.created asc ";
		List<String> params = new ArrayList<String>();
		
		params.add(WebTools.getCurrentBankId());
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.name like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(),page);
		return list;
	}
	//领用
	public List<Map<String, Object>> selectSealGetList(String srh_name,Page page) {
		String sql = "select t.*,tu.uname from t_seal t "
				+ " left join t_seal_user ts on t._id=ts.seal_id and ts.status=0 and ts.flag in('使用中','已领取','待归还') "
				+ " left join t_user tu on tu._id=ts.use_user_id and ts.status=0 "
				+ " where t.status=0 and t.bank_id=? and t.name like ?  and t.flag='启用' order by t.created asc ";
		List<String> params = new ArrayList<String>();
		
		params.add(WebTools.getCurrentBankId());
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.name like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(),page);
		return list;
	}
	//停用
	public List<Map<String, Object>> selectSealStopList(String srh_name,Page page) {
		String sql = "select t.* from t_seal t "
				+ " where t.status=0 and t.bank_id=? and t.name like ? and t.flag='启用' and  t.flag_use='未领取' order by t.created asc ";
		List<String> params = new ArrayList<String>();
		
		params.add(WebTools.getCurrentBankId());
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.name like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(),page);
		return list;
	}
	
	
	public List<Map<String,Object>> selectSealUserList(){
		
		String sql ="select t._id,t.uname from t_user t "
				+ " where t.status=0 and t.bank_id=? order by t.uname desc";
		
		List<Map<String,Object>> list = jt.queryForList(sql,new String[]{WebTools.getCurrentBankId()});
		
		return list;
	}
	
	//印控仪
	public List<Map<String,Object>> selectSealMacList(){
		
		String sql ="select t._id,t.code from t_mac t "
				+ " where t.status=0 and t.bank_id=? and t.flag='启用' order by t.code desc";
		
		List<Map<String,Object>> list = jt.queryForList(sql,new String[]{WebTools.getCurrentBankId()});
		
		return list;
	}
	
	//人员拥有印章
	public List<Map<String,Object>> selectSealList(String user_id){
		
		String sql ="select t.seal_id,ts.name from t_seal_user t "
				+ " left join t_seal ts on t.seal_id=ts._id "
				+ " where t.status=0 and t.use_user_id=? and ts.flag_use_status='已安装' and t.flag='使用中' and t.bank_id=? ";
		
		List<Map<String,Object>> list = jt.queryForList(sql,new String[]{user_id,WebTools.getCurrentBankId()});
		
		return list;
	}
	
	//查找当前t_seal_user
	public t_seal_user selectGetSealUser(String seal_id){
		
		String sql = "select t.* from t_seal_user t "
				+ " where t.status=0 and t.seal_id=? and t.flag in ('已领取','使用中') ";
		
		List<Map<String,Object>> list = jt.queryForList(sql,new String[]{seal_id});
		String id = list.get(0).get("_id")+"";
		t_seal_user user = super.findObjById(id, t_seal_user.class);
		return user;
		
	}
	//查找当前使用中t_seal_user_use
	public t_seal_user_use selectGetSealUserUse(String seal_id){
		
		String sql = "select t.* from t_seal_user_use t "
				+ " join t_seal_user tu on tu.status=0 and t.seal_user_id=tu._id "
				+ " where t.status=0 and t.seal_id=? and t.bank_id=? and t.flag='已安装' ";
		
		List<Map<String,Object>> list = jt.queryForList(sql,new String[]{seal_id,WebTools.getCurrentBankId()});
		String id = "";
		if(ChkTools.isNotNull(list)){
			id = list.get(0).get("_id")+"";
		}
		
		t_seal_user_use user = super.findObjById(id, t_seal_user_use.class);
		return user;
		
	}
	
	//查找印章详细信息
	public List<Map<String,Object>> selectSealDetail(String seal_use_id){
		
		String sql = "select tus.uname,tm.code,t.position from t_seal_user_use t "
				+ " left outer join t_user tus on tus.status=0 and t.use_user_id=tus._id "
				+ " left outer join t_mac tm on tm.status=0 and t.mac_id=tm._id "
				+ " where t.status=0 and t._id=? and tu.flag='使用中' ";
		
		List<Map<String,Object>> list = jt.queryForList(sql,new String[]{seal_use_id});
		
		return list;
		
	}
	//印章状态
	public List<Map<String, Object>> selectSealUserList(String srh_name,String bank_id,Page page) {
		String sql = "select t.* from t_seal t "
				+ " where t.status=0 and t.bank_id=? and t.name like ? order by t.created asc ";
		List<String> params = new ArrayList<String>();
		if(ChkTools.isNull(bank_id)){
			sql = sql.replace("and t.bank_id=?", "");
		}else{
			params.add(bank_id);
		}
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.name like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(),page);
		return list;
	}
	//印章保管人
	public List<Map<String, Object>> selectSealUserChkList(String srh_name,String bank_id,Page page) {
		String sql = "select t.*,tu.uname from t_seal t "
				+ " left outer join t_user tu on t.save_user_id=tu._id and tu.status=0 "
				+ " where t.status=0 and t.bank_id=? and t.name like ? order by t.created asc ";
		List<String> params = new ArrayList<String>();
		if(ChkTools.isNull(bank_id)){
			sql = sql.replace("and t.bank_id=?", "");
		}else{
			params.add(bank_id);
		}
	
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.name like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(),page);
		return list;
	}
	
	//印章日志
	public List<Map<String, Object>> selectSealUserLogList() {
		String sql = "select t.seal_code,t.seal_type,t.seal_modle_code,t.mac_code,t.file_id,t.file_id_before,t.file_id_user,t.flag,t.seal_time,tu.uname from t_seal_log t "
				+ " left outer join t_user tu on t.user_id=tu._id and tu.status=0 "
				+ " where t.status=0 and t.bank_id=? and t.user_id=? order by t.created asc ";
		List<String> params = new ArrayList<String>();
		params.add(WebTools.getCurrentBankId());
		params.add(WebTools.getCurrentUserId());
		
		List<Map<String, Object>> list = jt.queryForList(sql,params.toArray());
		return list;
	}
	
	//判断盖章是否在销毁权限之上
	@Transactional
	public boolean checkIsTop(String seal_id){
		int lev = bService.getBankLevel(WebTools.getCurrentBankId());
		int seal_lev = sService.checkSealTpyeLevel(seal_id);
		
		return lev<=seal_lev;
	}
	

	@Transactional
	public String file_id(String json) throws IOException{
		
		int year = DateTools.getYear();
		int month = DateTools.getMonth();
		String folder = year + File.separator + month;
		String folder_url = year + "/" + month;
		String filename = System.currentTimeMillis() + ".jpeg";
		t_file tf = new t_file();
		// 保存文件
		tf.setFile_name(filename);
		tf.setNew_file_name(filename);
		tf.setFolder(folder);
		tf.setFolder_url(folder_url);
		tf.setContent_type("image/jpeg");
		
		OutputStream out = null;
		if (json != null) {
			try {
				// Base64解码
				byte[] b = new BASE64Decoder().decodeBuffer(json);
				for (int i = 0; i < b.length; ++i) {
					if (b[i] < 0) {// 调整异常数据
						b[i] += 256;
					}
				}
				File newFile = new File(Config.DATA_PATH + File.separator
						+ folder + File.separator + tf.getNew_file_name());
				if (!newFile.getParentFile().exists()) {
					newFile.getParentFile().mkdirs();
				}
				// 生成jpeg图片
				String imgFilePath = Config.DATA_PATH + File.separator + folder
						+ File.separator + tf.getNew_file_name();// 新生成的图片

				super.saveObj(tf);
				
				out = new FileOutputStream(imgFilePath);
				out.write(b);
			} catch (Exception e) {
				e.printStackTrace();
				return "false";
			} finally {
				out.close();
			}
		
		}
		
		return tf.get_id();
	}
	
	public String getPath(String file_id){
		String path = "";
		t_file oldFile = (t_file) super.findObjById(file_id, t_file.class);
		if (oldFile != null) {
			path = Config.DATA_PATH + File.separator
					+ oldFile.getFolder()+"\\"+oldFile.getNew_file_name();
		}
		
		return path;
	}
	

	@Transactional
	public boolean stopSeal(String seal_id, String type) {
		t_seal seal = super.findObjById(seal_id, t_seal.class);
		seal.setFlag("停用");
		seal.setFlag_stop(type);
		super.updateObj(seal);
		
		t_seal_stop tst = new t_seal_stop();
		tst.setSeal_id(seal.get_id());
		tst.setBank_id(WebTools.getCurrentBankId());
		tst.setUser_id(WebTools.getCurrentUserId());
		tst.setFlag_stop(type);
		super.saveObj(tst);
		
		return true;
	}
	
	//印章停用
	
	public static void main(String[] args) {
		SealSetService s = SpringTools.getBean(SealSetService.class);
//		t_user user = s.findObjById("4028814a4b25516c014b259ad95b0064", t_user.class);
//		user.setUser_flag("正常");
//		s.updateObj(user);
		String p1 = s.getPath("4028814e4d311e68014d31f8ba2e00d6");
		String p2 = s.getPath("4028814e4d311e68014d31f64ec000d2");
		System.out.println(p1);
		System.out.println(p2);
		System.out.println(BMPLoader.compareImage(p1, p2));
		
	}
	
	
}
